<template>
  <div>
    <h1>用户信息管理</h1>
    <el-input v-model="searchQuery" placeholder="搜索用户..." @input="handleSearch" style="width: 300px; margin-bottom: 10px;"></el-input>
    <el-button @click="addUser">新增用户</el-button>
    <el-button @click="exportUsers">导出用户</el-button>

    <el-table :data="paginatedUsers" style="width: 100%" @sort-change="handleSortChange">
      <el-table-column prop="id" label="用户ID" width="180"></el-table-column>
      <el-table-column prop="name" label="用户名" width="180"></el-table-column>
      <el-table-column prop="email" label="邮箱" width="180"></el-table-column>
      <el-table-column label="操作" width="300">
        <template slot-scope="scope">
          <el-button size="mini" @click="viewUser(scope.row)">查看</el-button>
          <el-button size="mini" @click="editUser(scope.row)">编辑</el-button>
          <el-button size="mini" type="danger" @click="deleteUser(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-pagination
      layout="prev, pager, next"
      :total="filteredUsers.length"
      :page-size="itemsPerPage"
      :current-page="currentPage"
      @current-change="handlePageChange"
    ></el-pagination>

    <el-dialog :title="dialogTitle" :visible.sync="dialogVisible">
      <el-form :model="selectedUser" label-width="80px">
        <el-form-item label="用户名">
          <el-input v-model="selectedUser.name"></el-input>
        </el-form-item>
        <el-form-item label="邮箱">
          <el-input v-model="selectedUser.email"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="saveUser">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      users: [], // 用户数据列表
      searchQuery: '', // 搜索查询字符串
      currentPage: 1, // 当前页码
      itemsPerPage: 10, // 每页显示的用户数量
      selectedUser: {}, // 当前选中的用户
      dialogVisible: false, // 对话框可见性
      dialogTitle: '', // 对话框标题
      sortKey: '', // 排序字段
      sortOrder: '', // 排序顺序
    };
  },
  computed: {
    filteredUsers() {
      let filtered = this.users.filter(user => user.name.toLowerCase().includes(this.searchQuery.toLowerCase()));
      
      if (this.sortKey) {
        filtered = filtered.sort((a, b) => {
          if (this.sortOrder === 'ascending') {
            return a[this.sortKey] < b[this.sortKey] ? -1 : 1;
          } else {
            return a[this.sortKey] > b[this.sortKey] ? -1 : 1;
          }
        });
      }

      return filtered;
    },
    totalPages() {
      return Math.ceil(this.filteredUsers.length / this.itemsPerPage);
    },
    paginatedUsers() {
      const start = (this.currentPage - 1) * this.itemsPerPage;
      const end = start + this.itemsPerPage;
      return this.filteredUsers.slice(start, end);
    },
  },
  methods: {
    handleSearch() {
      this.currentPage = 1; // 搜索时重置到第一页
    },
    addUser() {
      this.selectedUser = { id: null, name: '', email: '' };
      this.dialogTitle = '新增用户';
      this.dialogVisible = true;
    },
    viewUser(user) {
      this.selectedUser = { ...user }; // 选择用户以显示详情
      this.dialogTitle = '查看用户';
      this.dialogVisible = true;
    },
    editUser(user) {
      this.selectedUser = { ...user }; // 复制用户数据以编辑
      this.dialogTitle = '编辑用户';
      this.dialogVisible = true;
    },
    deleteUser(user) {
      this.$confirm(`是否删除用户 ${user.name}?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.users = this.users.filter(u => u.id !== user.id);
        this.$message.success('删除成功!');
      }).catch(() => {
        this.$message.info('已取消删除');
      });
    },
    exportUsers() {
      // 实现导出用户逻辑，这里简单打印一下
      console.log('导出用户: ', this.users);
      this.$message.success('导出成功!');
    },
    handlePageChange(newPage) {
      this.currentPage = newPage;
    },
    handleSortChange({ column, prop, order }) {
      this.sortKey = prop;
      this.sortOrder = order;
    },
    saveUser() {
      if (this.selectedUser.id === null) { // 新增用户
        const newId = this.users.length ? this.users[this.users.length - 1].id + 1 : 1;
        this.users.push({ id: newId, ...this.selectedUser });
        this.$message.success('新增成功!');
      } else { // 编辑用户
        const index = this.users.findIndex(user => user.id === this.selectedUser.id);
        if (index !== -1) {
          this.users[index] = { ...this.selectedUser };
          this.$message.success('修改成功!');
        }
      }
      this.dialogVisible = false;
    },
  },
  mounted() {
    // 模拟获取用户数据
    this.users = [
      { id: 1, name: '张三', email: 'zhangsan@example.com' },
      { id: 2, name: '李四', email: 'lisi@example.com' },
      // 更多用户数据...
    ];
  },
};
</script>

<style scoped>
/* 添加一些基本样式 */
.el-pagination {
  margin-top: 10px;
}
</style>
